package top.serms.leetcode;

import java.util.List;

/**
 * @Author: SerMs
 * @Date: 2024/07/06 16 00
 * @Email: 1839928782@qq.com
 * @Blog: https://serms.top
 **/
public class LeetCode3101 {
    /**
     * 分析:
     * 1. 二进制的数组  只包含0和1
     */
    public static long countAlternatingSubarrays(int[] nums) {
        int count = 0;
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            boolean isAlternating = true;
            for (int j = i; j < n; j++) {
                if (j > i && nums[j] == nums[j - 1]) {
                    isAlternating = false;
                }
                if (isAlternating) {
                    count++;
                }
            }
        }
        return count;
    }

    /**
     * 暴力枚举 会超时
     *
     * @param nums
     * @return
     */
    public static long countAlternatingSubarrays2(int[] nums) {
        int count = 0;
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            count++;
            boolean isAlternating = true;
            for (int j = i + 1; j < n; j++) {
                if (nums[j] == nums[j - 1]) {
                    isAlternating = false;
                }
                if (isAlternating) {
                    count++;
                }
            }
        }
        return count;
    }

    // 遍历
    public static int countAlternatingSubarrays3(int[] nums) {
        int res = 0, cur = 0;
        int pre = -1;
        for (int a : nums) {
            cur = (pre != a) ? cur + 1 : 1;
            pre = a;
            res += cur;
        }

        return cur;
    }

    public static void main(String[] args) {

        int[] arr = {0, 1, 1, 1};
        System.out.println(countAlternatingSubarrays3(arr));
    }
}
